package com.labofjet.system.controller;

import com.labofjet.common.dto.ContextDto;
import com.labofjet.common.util.JSONUtils;
import com.labofjet.system.dto.SysLoginDto;
import com.labofjet.system.dto.SysUserDto;
import com.labofjet.system.enums.ESessionDefine;
import com.labofjet.system.service.impl.SysLoginServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;

@RestController
public class SysLoginController extends CrudBaseController {

	@Autowired
	private SysLoginServiceImpl sysLoginService;

	@RequestMapping(value = "/login", method = RequestMethod.POST)
	public ContextDto login(@RequestBody ContextDto contextDto, HttpSession session) {
		contextDto.setSuccess(true);
		if (!sysLoginService.accountProtect(contextDto)) {
			return contextDto;
		}
		SysLoginDto sysLoginDto = sysLoginService.login(contextDto);
		if (!contextDto.getSuccess()) { // 有错误
			sysLoginService.incrTimesForAccoutLoginError(contextDto);
			return contextDto;
		}

		sysLoginService.clearLoginFailCache(sysLoginDto.getSysUserDto());
		session.setAttribute(ESessionDefine.CURRENT_USER.getCode(), sysLoginDto.getSysUserDto());

		contextDto.setData(sysLoginDto);
		return contextDto;
	}

	@RequestMapping(value = "/unlock", method = RequestMethod.POST)
	public ContextDto unlock(@RequestBody ContextDto contextDto, HttpSession session) {
		contextDto.setSuccess(true);
		if (!sysLoginService.accountProtect(contextDto)) {
			return contextDto;
		}
		SysUserDto pwUser = JSONUtils.getRequestData(contextDto, SysUserDto.class);
		SysUserDto sysUserDto = (SysUserDto) session.getAttribute(ESessionDefine.CURRENT_USER.getCode());
		if (!sysUserDto.getPassword().equals(pwUser.getPassword())) {
			contextDto.setSuccess(false);
			contextDto.setMessage("密码错误");
			sysLoginService.incrTimesForAccoutLoginError(contextDto);
			return contextDto;
		}

		sysLoginService.clearLoginFailCache(sysUserDto);
		return contextDto;
	}

	@RequestMapping(value = "/logout", method = RequestMethod.POST)
	public ContextDto logout(@RequestBody ContextDto contextDto, HttpSession session) {
		contextDto.setSuccess(true);
		SysLoginDto sysLoginDto = sysLoginService.logout(contextDto);

		session.invalidate();

		contextDto.setData(sysLoginDto);
		return contextDto;
	}
}
